﻿using AccessTeamWorkflow.CommonHelpers;
using AccessTeamWorkflow.EntityHelpers;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Workflow;
using System;
using System.Activities;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AccessTeamWorkflow
{
    public class GetAccessTeamByName : CodeActivity
    {
        #region Input Parameters
        [RequiredArgument]
        [Input("Access Team Template Name")]
        public InArgument<string> AccessTeamTemplateName { get; set; }
        #endregion

        #region Output Parameters
        [Output("Is Access Team Template Exist")]
        public OutArgument<bool> IsExist { get; set; }

        [Output("Access Team")]
        [ReferenceTarget("teamtemplate")]
        public OutArgument<EntityReference> AccessTeam { get; set; }
        #endregion

        protected override void Execute(CodeActivityContext executionContext)
        {
            try
            {
                //Create the context and tracing service
                IExecutionContext context = executionContext.GetExtension<IExecutionContext>();
                IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
                ITracingService tracer = executionContext.GetExtension<ITracingService>();

                var accessTeamHelper = new AccessTeamHelper(service);
                tracer.Trace("GetAccessTeamByName:: Calling FindAccessTeamByName");


                var accessTeamResult = accessTeamHelper.FindAccessTeamByName(AccessTeamTemplateName.Get(executionContext));

                tracer.Trace("GetAccessTeamByName:: Found the Access Team template");
                // Set the access team
                AccessTeam.Set(executionContext, accessTeamResult);
                IsExist.Set(executionContext, (accessTeamResult != null));                
            }
            catch (Exception ex)
            {
                Helpers.Throw(String.Format("An error occurred in the {0} Custom Workflow Activity.",
                       this.GetType().ToString()),
                     ex);
            }
        }
    }
}
